﻿namespace My.Hydrator.Conventions
{
    using System;
    using System.ComponentModel.Composition;

    [Export(typeof(ITypeConvention))]
    public class FloatTypeConvention : BaseTypeConvention, ITypeConvention
    {
        public Type Type
        {
            get { return typeof(float); }
        }

        public object GenerateValue(object[] customAttributes)
        {
            this.GetAttributes(customAttributes);

            float result = 0;

            if (this.IsDataTypeAttributePresent)
            {
                var formatter = this.GetFormatter(DataTypeAttribute);
                if (formatter != null)
                {
                    return formatter.GetFormat();
                }
            }
            else if (this.IsRangeAttributePresent)
            {
                var min = double.Parse(RangeAttribute.Minimum.ToString());
                var max = double.Parse(RangeAttribute.Maximum.ToString());

                var intMax = (int)max - 1;
                result = (float)(this.Random.Next((int)min, intMax < 0 ? 0 : intMax) + this.Random.NextDouble());
            }
            else
            {
                result = this.Random.Next();
            }

            return result;
        }
    }
}
